#!/bin/sh
#
# /etc/rc.d/rc.elasticsearch -- startup script Slackware Linux for Elasticsearch
#
# Written by Daniel Romero <infoslack@gmail.com>.
#
# This script requires a 'elasticsearch' user/group to exist before running.
# The recommended UID/GID is 280. You can create these like so:
# groupadd -g 280 elasticsearch
# useradd -u 280 -g elasticsearch -s /bin/sh elasticsearch

set -e

# set params
PATH=/bin:/usr/bin:/sbin:/usr/sbin:$JAVA_HOME/bin:$JAVA_HOME/jre/bin
NAME=elasticsearch
DEFAULT=/etc/default/$NAME
ES_HOME=/usr/share/$NAME
ES_USER=$NAME
ES_GROUP=$NAME
LOG_DIR=/var/log/$NAME
DATA_DIR=/var/lib/$NAME
WORK_DIR=$DATA_DIR/data
CONF_DIR=/etc/$NAME
CONF_FILE=$CONF_DIR/elasticsearch.yml
PID_FILE=/var/run/$NAME.pid
DAEMON=$ES_HOME/bin/$NAME
MAX_OPEN_FILES=65535
DAEMON_OPTS="-d -p $PID_FILE --default.config=$CONF_FILE --default.path.home=$ES_HOME --default.path.logs=$LOG_DIR --default.path.data=$DATA_DIR --default.path.work=$WORK_DIR --default.path.conf=$CONF_DIR"

# overwrite settings from default file
if [ -f "$DEFAULT" ]; then
	. "$DEFAULT"
fi

# Check DAEMON exists
test -x $DAEMON || exit 0

case "$1" in
  start)
	  echo "Starting $NAME"
	  touch "$PID_FILE" && chown "$ES_USER":"$ES_GROUP" "$PID_FILE"
	  sudo -u $ES_USER sh -c "$DAEMON $DAEMON_OPTS"
	;;

  stop)
	  if [ -f "$PID_FILE" ]; then
      `cat $PID_FILE | xargs kill -9`
		  if [ $? -eq 1 ]; then
			  echo "$DESC is not running but pid file exists, cleaning up"
		  elif [ $? -eq 3 ]; then
			  PID="`cat $PID_FILE`"
			  echo "Failed to stop $NAME (pid $PID)"
			  exit 1
		  fi
		    rm -f "$PID_FILE"
	    else
		    echo "(not running)"
	  fi
	  echo "Stop $NAME"
	;;

  restart)
	  if [ -f "$PID_FILE" ]; then
		  $0 stop
		  sleep 1
	  fi
	  $0 start
	;;

  *)
	  echo "Usage: $0 {start|stop|restart}"
	  exit 1
	;;

esac
exit 0
